package com.atwei.mango.system.commen.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atwei.mango.system.securityHandler.SysAccount;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.*;

/**
 * @Classname JWTUtil
 * @Description
 * @Date 2022/6/9 15:53
 * @Author liuwei
 */
@Log4j2
public class JWTUtil {
    /**
     * @Description 签发token
     * @Author liuwei
     * @Date 2022/6/9 18:17
     * @params [com.atwei.mango.system.securityHandler.SysAccount]
     * @return java.lang.String
     **/
    public static String createAccessToken(SysAccount sysAccount){
        // 设置JWT
        return Jwts.builder()
                // 用户Id
                .setId(String.valueOf(sysAccount.getId()))
                // 主题
                .setSubject(sysAccount.getUsername())
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("mango")
                // 过期时间
                .setExpiration(new Date(System.currentTimeMillis() + JWTConfig.EXPIRATION))
                // 签名算法、密钥
                .signWith(SignatureAlgorithm.HS512, JWTConfig.SECRET)
                // todo
                // 自定义其他属性，如用户组织机构ID，用户所拥有的角色，用户权限信息等
//                .claim("authorities", JSON.toJSONString(sysAccount.getAuthorities()))
                .compact();
    }

    public static SysAccount parseAccessToken(String token) {
        SysAccount sysAccount = null;
        if (StringUtils.isNotEmpty(token)) {
            try {
                // 去除JWT前缀
                token = token.substring(JWTConfig.TOKEN_PREFIX.length());

                // 解析Token
                Claims claims = Jwts.parser().setSigningKey(JWTConfig.SECRET).parseClaimsJws(token).getBody();

                // 获取用户信息
                sysAccount = new SysAccount();
                sysAccount.setId(Integer.parseInt(claims.getId()));
                sysAccount.setAccountName(claims.getSubject());
                // todo
                // 获取其他属性，如用户组织机构ID，用户所拥有的角色，用户权限信息等
//                Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
//                String authority = claims.get("authorities").toString();
//                if (StringUtils.isNotEmpty(authority)) {
//                    List<Map<String, String>> authorityList = JSON.parseObject(authority,
//                            new TypeReference<List<Map<String, String>>>() {
//                            });
//                    for (Map<String, String> role : authorityList) {
//                        if (!role.isEmpty()) {
//                            authorities.add(new SimpleGrantedAuthority(role.get("authority")));
//                        }
//                    }
//                }
//                sysAccount.setAuthorities(authorities);
            } catch (Exception e) {
                log.error("解析Token异常：" + e);
            }
        }
        return sysAccount;
    }

}
